import { MongoClientOptions } from "mongodb";
import { ChatMessageType, FetchRenderProps } from "./interfaces";
import { IncomingHttpHeaders } from 'http'

const filepath = process.env.APP_CONFIG_FILE || '../config.json'

export interface SystemConfig {
  port: number;
  publicPath: string;
  /** 文件缓存目录 */
  cacheRoot: string;
  /** 文件上传大小限制，单位：K */
  maxUploadSize: number,
  server: {
    base: string;
    logout: string;
    admin: string;
    check: {
      /** 跳过登录的token, 取headers的access_token 和 access_username */
      access_token?: string;

      method: string;
      /** 登录验证URL */
      url: string;
      /** 凭条所在headers位置，通常为cookie */
      headers_key: string;
      mapping: {
        /** 映射登录用户账户 */
        username: string;
        /** 映射登录用户姓名 */
        name: string;
      },
      /** 验证失败 跳转登录地址 */
      login?: string;
    };
    users: {
      method: string;
      /** 获取所有用户列表 */
      url: string;
      body?: string;
      headers?: IncomingHttpHeaders;
      mapping: {
        /** 映射用户列表路径 */
        users: string;
        /** user.* 均为users子路径 */
        "user.username": string;
        "user.name": string;
        /** 映射分组信息 */
        "user.group": string;
        /** 头像 */
        "user.avatar": string;
      }
    }
  };
  mongodb: {
      uri?: string;
      dbName: string;
      config?: MongoClientOptions;
  };
  client?: {
    /** 默认sse */
    listenType?: 'sse' | 'loop' | 'ws';
    /** listenType 为loop时，设置的轮询时间，默认500 */
    loopTimeout?: number;
    /** 文件hash方式, 默认是：md5，可以支持断点续传 */
    hashType?: 'md5' | 'uuid';
    headers?: Record<string, string>;
    /** 开启加密 */
    encrypt?: boolean;
    /** 无需配置，运行时服务端生成动态key交给前端使用 */
    encrypt_key?: string;
  },
  robots?: {
    url: string;
    headers?: IncomingHttpHeaders
    body?: object;
    mapping: string;
    name: string;
    avatar: string;
    error_msg: string;
  }[];
  plugins?: ConfigPlugin[]
}
const config: SystemConfig = require(filepath)

export type ConfigPlugin<T extends ChatMessageType = ChatMessageType> = T extends infer K extends ChatMessageType ? {
  type: K;
  regexp: string;
  matches: readonly ['body', ...string[]];
  render?: K extends ChatMessageType.LINK_WITH_TITLE ? FetchRenderProps : never;
} : never

export default config
